import { getPageTitle } from '@/utils';

// 根据高端理财code获取中文和英文
export function transSeniorCode (code, dictionary) {
  const CODE = code;
  const CN = dictionary.SENIOR_TYPE_CODE_CN[CODE];
  const EN = Object.entries(dictionary.SENIOR_TYPE_EN_CODE).filter(item => {
    return item[1] === CODE;
  })[0][0];
  return {
    CODE,
    CN,
    EN
  };
}

// 根据公募基金code获取中文和英文
export function transPublicfundCode (code, dictionary) {
  const CODE = code;
  const CN = dictionary.PUBLICFUND_TYPE_CODE_CN[CODE];
  const EN = Object.entries(dictionary.PUBLICFUND_TYPE_EN_CODE).filter(item => {
    return item[1] === CODE;
  })[0][0];
  return {
    CODE,
    CN,
    EN
  };
}

/**
 * 根据输入的产品列表，返回高端理财类型
 * @param {Array} prodList - 产品列表
 * @returns {CODE, CN, EN} 类型编码，类型中文名，类型英文名
 */
export function transSeniorCodeFromList (prodList, dictionary) {
  if (!prodList.length) return {};
  // 如果仅有一条数据，返回此条数据的类型
  if (prodList.length === 1) return transSeniorCode(prodList[0].prodcode_type || prodList[0].prodType, dictionary);

  // 如果有多条数据，获取每条的产品类型
  const typeArr = prodList.map(item => item.prodcode_type);
  // 产品类型去重
  const ignoreArr = [...new Set(typeArr)];
  if (ignoreArr.length > 1) {
    return {
      CODE: '',
      CN: '高端理财',
      EN: ''
    };
  } else {
    return transSeniorCode(prodList[0].prodcode_type, dictionary);
  }
}

// 获取动态路由标题
export function getDynamicTitle (router, dictionary) {
  const { name = '', meta = {}, params = {} } = router;
  const DynamicRouterName = [
    'seniorList'
  ];
  const isDynamic = name && DynamicRouterName.includes(name);
  if (!isDynamic) return;
  const { type } = params;
  // 高端理财
  const SENIOR_TYPE_CODE = dictionary.SENIOR_TYPE_EN_CODE[type];
  const SENIOR_TYPE_CN = dictionary.SENIOR_TYPE_CODE_CN[SENIOR_TYPE_CODE];
  // meta.title作为后缀
  const suffix = meta.title;
  return SENIOR_TYPE_CN + suffix;
}

// 设置动态路由标题
export function setDynamicTitle (router, dictionary) {
  const dynamicTitle = getDynamicTitle(router, dictionary);
  if (dynamicTitle) {
    document.title = getPageTitle(dynamicTitle);
  }
}

// 字典数组转对象
// [{value: 1, label: 'a'}] => { 1: a }
export function generateObject (dict) {
  const result = {};
  for (const k in dict) {
    const items = dict[k];
    result[k] = items.reduce((res, next) => {
      const { value, label } = next;
      res[value] = label;
      return res;
    }, {});
  }
  return result;
}
